package com.example.game_community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.game_community.entity.Post;
import com.example.game_community.entity.User;
import com.example.game_community.mapper.SearchMapper;
import com.example.game_community.service.PostService;
import com.example.game_community.service.SearchService;
import com.example.game_community.service.UserService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl extends ServiceImpl<SearchMapper, Post> implements SearchService {

    @Autowired
    PostService postService;

    @Autowired
    UserService userService;

    @Override
    public List<Post> getSearchList(String keyword) {
        return baseMapper.selectList(buildQueryWrapper(keyword));
    }

    @Override
    public Page<Post> search(String keyword, int page, int pageSize) {
        Page<Post> pageInfo = new Page<>(page, pageSize);
        Page<Post> resultPage = baseMapper.selectPage(pageInfo, buildQueryWrapper(keyword));
        List<Post> posts = resultPage.getRecords(); // 新增：获取分页数据
        
        buildUserInfo(posts);
        extractPostImages(posts);  // 修正：添加参数
        return resultPage;
    }

    // 新增：统一查询条件构建方法
    private LambdaQueryWrapper<Post> buildQueryWrapper(String keyword) {
        LambdaQueryWrapper<Post> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Post::getTitle, keyword)
              .or()
              .like(Post::getContent, keyword);
        return wrapper;
    }

    private void extractPostImages(List<Post> posts){
        posts.forEach(post -> {
            List<String> imgUrls = extractImageUrls(post.getContent());
            post.setImageUrls(imgUrls);
        });
    }

    private List<String> extractImageUrls(String html){
        Document doc = Jsoup.parse(html);
        Elements images = doc.select("img");
        // 修正：过滤空值并去重
        return images.stream()
                .map(img -> img.attr("src"))
                .filter(url -> !url.isEmpty())
                .distinct()
                .collect(Collectors.toList());
    }

    private void buildUserInfo(List<Post> posts) {
       if (posts.isEmpty()){
           return;
       }
       
       Set<Long> authorIds = posts.stream().map(Post::getAuthorId)
               .collect(Collectors.toSet());

       Map<Long,User> userMap = userService.listByIds(authorIds).stream()
               .collect(Collectors.toMap(User::getId, Function.identity()));

       posts.forEach(post -> post.setUserInfo(userMap.get(post.getAuthorId())));
    }
}
